<template>
  <div class="card-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <span class="search-label">学期：</span>
      <el-select
        v-model="params.termName"
        placeholder="请输入或选择"
        clearable
        filterable
        @blur="selectBlur"
        @clear="selectClear"
        @change="selectChange"
      >
        <el-option
          v-for="(item, index) in terms"
          :key="index"
          :label="item.termName"
          :value="item.termName"
        />
      </el-select>
      <el-button type="primary" class="search-btn" @click="search"
        >查询</el-button
      >
    </div>
    <!-- 新增删除操作区域 -->
    <div class="create-container">
      <el-button type="primary" @click="handleAdd">添加</el-button>
      <el-button @click="batchDelete" >批量删除</el-button>
      <el-button @click="handleExportExcel">导出excel表</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table
        style="width: 100%"
        :data="list"
        @selection-change="handleSelectionChange"
      >
      <el-table-column
          type="selection"
          width="55"
         />
        <el-table-column type="index" label="序号" :index="indexMethod" width="300"/>
        <el-table-column label="学期" prop="termName"/>
        <el-table-column label="操作" fixed="right" width="90">
          <template #default="scope">
            <el-button size="mini" type="text" @click="edit(scope.row.termId,scope.row.termName)">编辑</el-button>
            <el-button size="mini" type="text" @click="deleteOne(scope.row.termId)" >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.page"
        :page-sizes="[2, 4, 6, 8]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 添加或修改操作日志记录对话框 -->
    <el-dialog :visible.sync="open" width="500px" append-to-body>
      <span slot="title">{{Form.termId?"修改学期信息":"添加学期信息"}}</span>
      <el-form ref="form" :model="Form" :rules="Rules" label-width="80px">
        <el-form-item label="学期名称" prop="termName">
          <el-input v-model="Form.termName" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="reset">重置</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAllTermsAPI,getAllTermsByPageAPI,addOrEditTermAPI,deleteTermAPI,exportExcelAPI } from "@/api/term";

export default {
  name: "Check_results",
  data() {
    return {
      Rules:{
        termName:[
          {
            required: true, message: '请输入学期', trigger: 'blur'
          }
        ]
      },
      Form:{
        termId:"",
        termName:"",
      },
      open: false,
      selecttionVal: [],
      terms: [],
      total: 0, //页总数
      list: [], //列表
      params: {
        //参数
        page: 1,
        pageSize: 2,
        termName: "",
      },
    };
  },
  created() {
    this.getAllTermsByPage()
    this.getAllTerms();
  },
  methods: {
    handleExportExcel() {
      exportExcelAPI(this.params)
        .then(response => {
          const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

          const link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = 'scores.xlsx';
          link.click();

          window.URL.revokeObjectURL(link.href);
        })
        .catch(error => {
          console.error('Failed to export Excel:', error);
        });
    },
    //单个删除
    deleteOne(id){
      this.$confirm('您确定要删除此数据吗?','提示').then(async()=>{
        // console.log('点击确定');
        await deleteTermAPI(id)
        this.$message.success('删除成功')
        if(this.list.length == 1 && this.params.page >1){
          this.params.page--
        }
        this.getAllTerms();
        this.getAllTermsByPage()
      }).catch(()=>{
        // console.log('点击取消');
      })
    },
    //批量删除
    batchDelete(){
      if(this.selecttionVal.length<=0){
        this.$message.warning('请先选择要删除的数据')
        return 
      }
      const ids = this.selecttionVal.map(item=>{
        return item.termId
      })
      this.$confirm('您确定要删除此数据吗?','提示').then(async()=>{
        // console.log('点击确定');
        await deleteTermAPI(ids.join(','))
        this.$message.success('批量删除成功')
        if(this.list.length == this.selecttionVal.length && this.params.page >1){
          this.params.page--
        }
        this.getAllTerms();
        this.getAllTermsByPage()
      }).catch(()=>{
        // console.log('点击取消');
      })
    },
    //获取选择的数据
    handleSelectionChange(val){
      this.selecttionVal = val
    },
    //提交表格
    submitForm() {
      this.$refs.form.validate(async (flag) => {
        if (!flag)
          return
        if (this.Form.termId!='') {
          //修改操作
          await addOrEditTermAPI(this.Form)
          this.$message.success('修改成功')
          this.getAllTerms();
        } else {
          //新增操作
          await addOrEditTermAPI(this.Form)
          this.$message.success('添加成功')
          this.getAllTerms();
          this.params.page=1
          this.reset();
        }
        this.open = false
        this.getAllTermsByPage()
      })
    },
    //编辑按钮
    async edit(termId,termName) {
      this.Form.termId = termId
      this.Form.termName = termName
      this.open = true
    },
    // 表单重置
    reset() {
      this.Form.termName = ''
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (this.Form.termId) {
        this.Form.termId = ''
        this.Form.termName = ''
      }
      this.open = true
    },
    //获取学期分页数据
    async getAllTermsByPage(){
      const res = await getAllTermsByPageAPI(this.params);
      this.total = res.data.total
      this.list = res.data.records
    },
    //获取学期列表
    async getAllTerms(){
      const res = await getAllTermsAPI();
      this.terms = res.data
    },
    //多选框输入值
    selectBlur(e) {
      // 意见类型
      if (e.target.value !== "") {
        this.params.termName = e.target.value;
        this.$forceUpdate(); // 强制更新
      }
    },
    //清空多选框
    selectClear() {
      this.params.termName = "";
      this.$forceUpdate();
    },
    //改变多选框
    selectChange(val) {
      this.params.termName = val;
      this.$forceUpdate();
    },
    //点击查询按钮
    search() {
      this.params.page = 1;
      this.getAllTermsByPage();
    },
    //计算序号
    indexMethod(index) {
      return (this.params.page - 1) * this.params.pageSize + index + 1;
    },
    //页数改变
    handleCurrentChange(val) {
      this.params.page = val;
      this.getAllTermsByPage();
    },
    //页条数改变
    handleSizeChange(val) {
      this.params.pageSize = val;
      this.getAllTermsByPage();
    },
  },
};
</script>


<style lang="scss" scoped>
.card-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-main {
    width: 220px;
    margin-right: 10px;
  }

  .search-btn {
    margin-left: 20px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>